<template>
  <div class="flow-container">
    <div class="container">
      <div class="timetable-wrapper">
        <div class="timetable-container">
          <div class="timetable-controls">
            <div class="semester-selector">
              <select
                v-model="selectedSemester"
                @change="
                  handleSemesterChange(
                    ($event.target as HTMLSelectElement).value
                  )
                "
              >
                <option
                  v-for="semester in semesters"
                  :key="semester.id"
                  :value="semester.id"
                >
                  {{ semester.name }}
                </option>
              </select>
            </div>
            <div class="week-navigation">
              <button class="nav-btn" @click="prevWeek" :disabled="isFirstWeek">
                <i class="icon-arrow-left"></i>
              </button>
              <span class="week-title"
                >第{{ currentWeekNumber }}周 {{ weekTitle }}</span
              >
              <button class="nav-btn" @click="nextWeek" :disabled="isLastWeek">
                <i class="icon-arrow-right"></i>
              </button>
            </div>
            <div class="action-buttons">
              <button class="add-btn" @click="openAddEventModal('course')">
                <i class="icon-plus"></i> 添加课程
              </button>
              <button class="add-btn" @click="openAddEventModal('schedule')">
                <i class="icon-plus"></i> 添加日程
              </button>
              <button class="sync-btn" @click="syncEvents" :disabled="syncing">
                {{ syncing ? "同步中..." : "同步数据" }}
              </button>
            </div>
          </div>

          <div class="divider"></div>

          <div class="timetable-container">
            <div class="timetable-header">
              <div class="time-column">时间</div>
              <div
                v-for="day in fixedWeekDays"
                :key="day.day"
                class="day-header"
                :class="{ today: day.isToday }"
              >
                {{ day.name }}<br />{{ formatDate(day.date) }}
              </div>
            </div>

            <div class="timetable-body">
              <div v-for="time in timeSlots" :key="time" class="timetable-row">
                <div class="time-slot">{{ time }}</div>
                <div
                  v-for="day in fixedWeekDays"
                  :key="day.day"
                  class="day-slot"
                  :class="{ 'current-time': isCurrentTime(day.day, time) }"
                >
                  <!-- 课程项 -->
                  <div
                    v-for="event in getEventsAt(day.day, time, 'course')"
                    :key="event.id"
                    class="course-item"
                    :style="{ backgroundColor: event.color }"
                    @click.stop="openEventDetail(event)"
                  >
                    <div class="course-name">{{ event.name }}</div>
                    <div class="course-time">
                      {{ formatTime(event.startTime) }}-{{
                        formatTime(event.endTime)
                      }}
                    </div>
                    <div class="course-location">{{ event.location }}</div>
                    <div class="course-teacher" v-if="event.teacher">
                      {{ event.teacher }}
                    </div>
                  </div>

                  <!-- 日程项 -->
                  <div
                    v-for="event in getEventsAt(day.day, time, 'schedule')"
                    :key="event.id"
                    class="schedule-item"
                    :style="getEventStyle(event, time)"
                    @click.stop="openEventDetail(event)"
                  >
                    <div class="schedule-name">{{ event.name }}</div>
                    <div class="schedule-time">
                      {{ formatTime(event.startTime) }}-{{
                        formatTime(event.endTime)
                      }}
                    </div>
                    <div class="schedule-location" v-if="event.location">
                      {{ event.location }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 统一事件模态框 -->
      <div v-if="showEventModal" class="modal-overlay">
        <div class="modal-content">
          <h3>
            {{
              editingEvent
                ? `编辑${newEvent.eventType === "course" ? "课程" : "日程"}`
                : `添加新${newEvent.eventType === "course" ? "课程" : "日程"}`
            }}
          </h3>
          <form @submit.prevent="saveEvent">
            <div class="form-group">
              <label>类型</label>
              <select v-model="newEvent.eventType" required>
                <option value="course">课程</option>
                <option value="schedule">日程</option>
              </select>
            </div>

            <div class="form-group">
              <label>{{
                newEvent.eventType === "course" ? "课程名称" : "日程标题"
              }}</label>
              <input v-model="newEvent.name" required />
            </div>

            <div class="form-group" v-if="newEvent.eventType === 'course'">
              <label>教师</label>
              <input v-model="newEvent.teacher" />
            </div>

            <div class="form-group">
              <label>描述</label>
              <textarea v-model="newEvent.description" rows="2"></textarea>
            </div>

            <div class="form-group">
              <label>地点</label>
              <input
                v-model="newEvent.location"
                :required="newEvent.eventType === 'course'"
              />
            </div>

            <div class="form-group">
              <label>星期</label>
              <select v-model="newEvent.dayOfWeek" required>
                <option
                  v-for="day in fixedWeekDays"
                  :key="day.day"
                  :value="day.day"
                >
                  {{ day.name }}
                </option>
              </select>
            </div>

            <div class="form-group time-group">
              <div>
                <label>开始时间</label>
                <input
                  type="time"
                  v-model="newEvent.startTime"
                  required
                  step="300"
                />
              </div>
              <div>
                <label>结束时间</label>
                <input
                  type="time"
                  v-model="newEvent.endTime"
                  required
                  step="300"
                />
              </div>
            </div>

            <div class="form-group">
              <label>颜色</label>
              <input type="color" v-model="newEvent.color" />
            </div>

            <div class="form-group">
              <label>重复周数</label>
              <div class="week-range">
                <select v-model="newEvent.startWeek" required>
                  <option
                    v-for="week in semesterWeeks"
                    :key="'start' + week"
                    :value="week"
                  >
                    第{{ week }}周
                  </option>
                </select>
                <span>至</span>
                <select v-model="newEvent.endWeek" required>
                  <option
                    v-for="week in semesterWeeks"
                    :key="'end' + week"
                    :value="week"
                  >
                    第{{ week }}周
                  </option>
                </select>
              </div>
            </div>

            <div class="form-actions">
              <button type="button" @click="showEventModal = false">
                取消
              </button>
              <button type="submit">保存</button>
              <button
                v-if="editingEvent"
                type="button"
                class="delete-btn"
                @click="deleteEvent"
              >
                删除
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useScheduleStore } from "../../stores/schedule";
import { useUserStore } from "../../stores/user";
import api from "../../api/request";
import { ElMessage } from "element-plus";

/*interface Event {
  id: string;
  userId: string;
  eventType: "course" | "schedule";
  name: string;
  teacher: string;
  description: string;
  location: string;
  dayOfWeek: number;
  startTime: string;
  endTime: string;
  startWeek: number;
  endWeek: number;
  semester: string;
  color: string;
  status: 0 | 1; // 0: 已删除, 1: 正常
  week: number;
}*/

interface WeekDay {
  day: number;
  name: string;
  date: Date;
  isToday: boolean;
}

interface Semester {
  id: string;
  name: string;
  startDate: string;
  endDate: string;
  weekCount: number;
}

const router = useRouter();
const scheduleStore = useScheduleStore();
const userStore = useUserStore();
type Event = ReturnType<typeof useScheduleStore>["events"][0];
const currentWeekStart = ref<Date>(new Date());
//const currentWeekNumber = ref<number>(1);
const syncing = ref<boolean>(false);
const events = ref<Event[]>([]);
//const semesters = ref<Semester[]>([]);
//const selectedSemester = ref<string>("");
const showEventModal = ref(false);
const editingEvent = ref<Event | null>(null);
const currentSemesterId = ref("");

// 使用用户ID初始化新事件
const newEvent = ref<Omit<Event, "id"> & { id?: number }>({
  id: undefined,
  userId: Number(userStore.id) || 0, // 从用户store获取ID
  eventType: "course",
  name: "",
  teacher: "",
  description: "",
  location: "",
  dayOfWeek: 2,
  startTime: "8:00",
  endTime: "9:40",
  color: "#5b6ee1",
  semester: "",
  startWeek: 1,
  endWeek: 1,
  status: 1,
});

// 时间槽
const timeSlots = [
  "8:00",
  "8:50",
  "9:50",
  "10:40",
  "11:30",
  "14:05",
  "14:55",
  "15:45",
  "16:40",
  "17:30",
  "18:30",
  "19:20",
  "20:10",
];

// 固定周一到周日的星期顺序（以周一为一周的开始）
const fixedWeekDays = computed<WeekDay[]>(() => {
  const days: WeekDay[] = [];
  const start = new Date(currentWeekStart.value);

  // 调整到本周的周一
  const monday = new Date(start);
  const dayOfWeek = monday.getDay();
  // dayOfWeek: 0=周日, 1=周一, ..., 6=周六
  // 如果是周日，往前推6天，否则往前推(dayOfWeek-1)天
  monday.setDate(start.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));

  for (let i = 0; i < 7; i++) {
    const date = new Date(monday);
    date.setDate(monday.getDate() + i);

    days.push({
      day: i + 1, // 1=周一, 2=周二, ..., 7=周日
      name: getDayName(i === 6 ? 0 : i + 1), // 0=周日, 1=周一, ..., 6=周六
      date: date,
      isToday: isSameDay(date, new Date()),
    });
  }

  return days;
});

// 计算属性
const isFirstWeek = computed(() => {
  return currentWeekNumber.value <= 1;
});

const isLastWeek = computed(() => {
  const semester = semesters.value.find((s) => s.id === selectedSemester.value);
  return semester ? currentWeekNumber.value >= semester.weekCount : false;
});

const weekTitle = computed(() => {
  const start = fixedWeekDays.value[0].date;
  const end = fixedWeekDays.value[6].date;
  return `${formatDate(start)} - ${formatDate(end)}`;
});

const semesterWeeks = computed(() => {
  const semester = semesters.value.find((s) => s.id === selectedSemester.value);
  if (!semester) return [];

  const weeks: number[] = [];
  for (let i = 1; i <= semester.weekCount; i++) {
    weeks.push(i);
  }
  return weeks;
});

// 方法
// 添加错误信息提取函数
const getErrorMessage = (error: unknown): string => {
  if (error instanceof Error) {
    return error.message;
  }
  if (typeof error === "string") {
    return error;
  }
  if (error && typeof error === "object" && "message" in error) {
    return String(error.message);
  }
  return "未知错误";
};

//学期星期显示
const academicYearConfig = {
  get currentYear() {
    const now = new Date();
    return now.getMonth() >= 8 ? now.getFullYear() : now.getFullYear() - 1;
  },
  semesters: {
    first: {
      name: (year: number) => `${year}-${year + 1}学年第一学期`,
      dateRange: (year: number) => ({
        start: new Date(year, 8, 9), // 9月9日
        end: new Date(year + 1, 0, 12), // 次年1月12日
      }),
    },
    second: {
      name: (year: number) => `${year}-${year + 1}学年第二学期`,
      dateRange: (year: number) => ({
        start: new Date(year + 1, 1, 17), // 次年2月17日
        end: new Date(year + 1, 5, 22), // 次年6月22日
      }),
    },
    third: {
      name: (year: number) => `${year}-${year + 1}学年第三学期`,
      dateRange: (year: number) => ({
        start: new Date(year + 1, 5, 23), // 次年6月23日
        end: new Date(year + 1, 6, 20), // 次年7月20日
      }),
    },
  },
};

const currentWeekNumber = ref(1);
const semesters = ref<
  Array<{
    id: string;
    name: string;
    startDate: Date;
    endDate: Date;
    weekCount: number;
  }>
>([]);
const selectedSemester = ref("");

const initializeAcademicCalendar = async () => {
  const currentYear = academicYearConfig.currentYear;
  const now = new Date();

  // 生成三个学期数据
  const generateSemester = (type: "first" | "second" | "third") => {
    let start: Date, end: Date;
    const year = academicYearConfig.currentYear;

    if (type === "first") {
      start = new Date(year, 8, 9); // 9月9日
      end = new Date(year + 1, 0, 12); // 次年1月12日
    } else if (type === "second") {
      start = new Date(year + 1, 1, 17); // 次年2月17日
      end = new Date(year + 1, 5, 22); // 次年6月22日
    } else {
      // 第三学期特殊处理
      start = new Date(2025, 5, 23); // 2025年6月23日
      end = new Date(2025, 6, 20); // 2025年7月20日
    }

    return {
      id: formatDateToYMD(start), // 使用安全格式化
      name: academicYearConfig.semesters[type].name(year),
      startDate: start,
      endDate: end,
      weekCount: calculateWeekCount(start, end),
    };
  };

  semesters.value = [
    generateSemester("first"),
    generateSemester("second"),
    generateSemester("third"),
  ];

  // 自动检测当前学期
  const currentSemester =
    semesters.value.find(
      (semester) => now >= semester.startDate && now <= semester.endDate
    ) || semesters.value[0]; // 默认显示第一学期

  selectedSemester.value = currentSemester.id;
  currentSemesterId.value = currentSemester.id; // 存储当前学期ID

  // 计算当前周数
  currentWeekNumber.value = Math.max(
    1,
    Math.min(
      calculateWeekNumber(now, currentSemester.startDate),
      currentSemester.weekCount
    )
  );

  console.log("当前学期状态:", {
    semester: currentSemester.name,
    week: currentWeekNumber.value,
    dateRange: [
      currentSemester.startDate.toLocaleDateString(),
      currentSemester.endDate.toLocaleDateString(),
    ],
  });

  await fetchEvents();
};

//学期切换
const handleSemesterChange = (semesterId: string) => {
  const targetSemester = semesters.value.find((s) => s.id === semesterId);
  if (!targetSemester) return;

  selectedSemester.value = semesterId;

  // 判断是否为当前日期所在的学期
  const now = new Date();
  const isCurrentSemester = semesterId === currentSemesterId.value;

  if (isCurrentSemester) {
    // 当前学期：显示实际周数
    const weekNum = calculateWeekNumber(now, targetSemester.startDate);
    currentWeekNumber.value = Math.max(
      1,
      Math.min(weekNum, targetSemester.weekCount)
    );
    currentWeekStart.value = getMondayOfWeek(now);
  } else {
    // 非当前学期：显示第一周
    currentWeekNumber.value = 1;
    currentWeekStart.value = getMondayOfWeek(targetSemester.startDate);
  }

  fetchEvents();
};

// 安全日期格式化工具
function formatDateToYMD(date: Date): string {
  return [
    date.getFullYear(),
    String(date.getMonth() + 1).padStart(2, "0"),
    String(date.getDate()).padStart(2, "0"),
  ].join("-");
}

// 辅助函数：计算总周数
const calculateWeekCount = (start: Date, end: Date) => {
  const msPerWeek = 604800000; // 7天的毫秒数
  return Math.ceil((end.getTime() - start.getTime()) / msPerWeek);
};

// 辅助函数：计算当前周数（基于周一）
const calculateWeekNumber = (current: Date, semesterStart: Date) => {
  const startMonday = getMondayOfWeek(semesterStart);
  const currentMonday = getMondayOfWeek(current);
  const diffWeeks = Math.round(
    (currentMonday.getTime() - startMonday.getTime()) / 604800000
  );
  return diffWeeks + 1;
};

// 获取当周周一
const getMondayOfWeek = (date: Date) => {
  const d = new Date(date);
  const day = d.getDay();
  const diff = d.getDate() - day + (day === 0 ? -6 : 1);
  return new Date(d.setDate(diff));
};

const prevWeek = () => {
  if (isFirstWeek.value) return;

  const newDate = new Date(currentWeekStart.value);
  newDate.setDate(newDate.getDate() - 7);
  currentWeekStart.value = newDate;
  currentWeekNumber.value--;
  fetchEvents();
};

const nextWeek = () => {
  if (isLastWeek.value) return;

  const newDate = new Date(currentWeekStart.value);
  newDate.setDate(newDate.getDate() + 7);
  currentWeekStart.value = newDate;
  currentWeekNumber.value++;
  fetchEvents();
};

// 获取事件
const fetchEvents = async () => {
  if (!selectedSemester.value || !userStore.id) {
    ElMessage.error("无法获取事件: 缺少学期ID或用户ID");
    return;
  }

  try {
    /*ElMessage.info(
      `正在获取事件，学期: ${selectedSemester.value}, 周数: ${currentWeekNumber.value}`
    );*/
    await scheduleStore.fetchEvents(
      Number(userStore.id),
      selectedSemester.value,
      currentWeekNumber.value
    );
    // 调试：打印所有事件
    console.log(
      "[调试] fetchEvents后 scheduleStore.events:",
      JSON.parse(JSON.stringify(scheduleStore.events))
    );
    ElMessage.success("事件获取成功");
  } catch (error) {
    console.error("获取事件失败:", error);
    ElMessage.error(`获取事件失败: ${getErrorMessage(error)}`);
  }
};

const syncEvents = async () => {
  syncing.value = true;
  try {
    await fetchEvents();
  } finally {
    syncing.value = false;
  }
};

// 获取事件（跨时间槽显示）
const getEventsAt = (
  day: number,
  timeSlot: string,
  type: "course" | "schedule"
): ReturnType<typeof useScheduleStore>["events"] => {
  // 当前时间槽的起止分钟
  const slotIndex = timeSlots.indexOf(timeSlot);
  if (slotIndex === -1) return [];
  const slotStart = getMinutes(timeSlots[slotIndex]);
  const slotEnd =
    slotIndex < timeSlots.length - 1
      ? getMinutes(timeSlots[slotIndex + 1])
      : getMinutes(timeSlots[slotIndex]) + 50; // 最后一个槽默认50分钟

  // 只返回与当前时间槽有重叠的事件
  return scheduleStore.events.filter((event) => {
    if (event.status === 0) return false;
    if (event.eventType !== type) return false;
    if (event.dayOfWeek !== day) return false;
    if (
      event.startWeek > currentWeekNumber.value ||
      event.endWeek < currentWeekNumber.value
    )
      return false;
    const eventStart = getMinutes(event.startTime);
    const eventEnd = getMinutes(event.endTime);
    // 判断事件与时间槽有重叠
    return eventStart < slotEnd && eventEnd > slotStart;
  });
};

// 辅助函数：将HH:mm转为分钟
function getMinutes(time: string): number {
  const [h, m] = time.split(":").map(Number);
  return h * 60 + m;
}

const getEventStyle = (event: Event, slotTime: string) => {
  if (event.eventType === "course") return {};

  // 计算持续时间（分钟）
  const duration = calculateDuration(event);

  // 计算相对于时间槽的偏移量（分钟）
  const offset = calculateOffset(slotTime, event.startTime);

  // 计算高度（1分钟 = 1px）
  const height = duration;

  // 计算顶部偏移（1分钟 = 1px）
  const top = offset;

  return {
    height: `${height}px`,
    top: `${top}px`,
    backgroundColor: event.color,
    maxHeight: `${100 - top}px`,
    overflow: "hidden",
  };
};

const calculateDuration = (event: Event) => {
  const [startH, startM] = event.startTime.split(":").map(Number);
  const [endH, endM] = event.endTime.split(":").map(Number);
  return endH * 60 + endM - (startH * 60 + startM);
};

const calculateOffset = (slotTime: string, startTime: string) => {
  const [slotH, slotM] = slotTime.split(":").map(Number);
  const [startH, startM] = startTime.split(":").map(Number);
  return startH * 60 + startM - (slotH * 60 + slotM);
};

const validateEventTime = () => {
  if (!newEvent.value.startTime || !newEvent.value.endTime) {
    return false;
  }

  const [startHour, startMinute] = newEvent.value.startTime
    .split(":")
    .map(Number);
  const [endHour, endMinute] = newEvent.value.endTime.split(":").map(Number);

  const startTotal = startHour * 60 + startMinute;
  const endTotal = endHour * 60 + endMinute;

  if (endTotal <= startTotal) {
    alert("结束时间必须晚于开始时间");
    newEvent.value.endTime = "";
    return false;
  }

  return true;
};

// 保存事件
const saveEvent = async () => {
  if (!newEvent.value.name || !userStore.id) {
    ElMessage.error("保存失败: 缺少事件名称或用户ID");
    return;
  }
  if (newEvent.value.eventType === "course" && !newEvent.value.location) {
    ElMessage.error("保存失败: 课程必须填写地点");
    return;
  }
  if (!validateEventTime()) {
    ElMessage.error("保存失败: 时间验证未通过");
    return;
  }

  try {
    ElMessage.info("正在保存事件...");
    if (editingEvent.value && editingEvent.value.id) {
      try {
        const result = await scheduleStore.updateEvent({
          ...newEvent.value,
          id: editingEvent.value.id,
        } as Event);

        console.log("Update result:", result);

        if (result === true) {
          // 简单成功情况
          ElMessage.success("更新成功");
          await fetchEvents(); // 刷新数据
        } else if (result && typeof result === "object") {
          // 返回了完整课程对象
          ElMessage.success(`${result.name} 更新成功`);
          // 可以在这里处理本地数据更新
        } else {
          ElMessage.warning("更新完成但未返回数据");
        }

        showEventModal.value = false;
      } catch (error) {
        console.error("更新错误:", error);
        ElMessage.error(`更新失败: ${getErrorMessage(error)}`);
      }
    } else {
      try {
        const createdEvent = await scheduleStore.createEvent({
          ...newEvent.value,
          userId: Number(userStore.id),
          semester: selectedSemester.value, // 确保学期信息传递
        });
        console.log(createdEvent);
        if (createdEvent?.id) {
          ElMessage.success({
            message: `事件创建成功! ID: ${createdEvent.id}`,
            duration: 3000,
          });
          showEventModal.value = false;
          await fetchEvents();
        } else {
          throw new Error("创建成功但返回数据不完整");
        }
      } catch (error) {
        console.error("事件创建错误详情:", error);
        ElMessage.error(`事件创建失败: ${getErrorMessage(error)}`);
      }
    }
  } catch (error) {
    console.error("保存事件全局错误:", error);
    ElMessage.error(`保存过程出错: ${getErrorMessage(error)}`);
    logApiError(error);
  }
};

const deleteEvent = async () => {
  if (editingEvent.value?.id) {
    const success = await scheduleStore.deleteEvent(editingEvent.value.id);
    showEventModal.value = false; // 无论成功与否都先关闭模态框
  }
  await fetchEvents(); // 删除后自动刷新课程表
};

// openAddEventModal 用于打开添加事件模态框
const openAddEventModal = (type: "course" | "schedule") => {
  newEvent.value = {
    id: undefined,
    userId: Number(userStore.id) || 0,
    eventType: type,
    name: "",
    teacher: "",
    description: "",
    location: "",
    dayOfWeek: 2,
    startTime: "8:00",
    endTime: "9:40",
    color: getRandomColor(),
    semester: selectedSemester.value,
    startWeek: currentWeekNumber.value,
    endWeek: currentWeekNumber.value,
    status: 1,
  };
  editingEvent.value = null;
  showEventModal.value = true;
};

const openEventDetail = (event: Event) => {
  newEvent.value = {
    ...event,
    id: event.id !== undefined ? Number(event.id) : undefined,
  };
  editingEvent.value = event;
  showEventModal.value = true;
};

const getRandomColor = (): string => {
  const colors = [
    "#5b6ee1",
    "#a259ec",
    "#4CAF50",
    "#2196F3",
    "#FF9800",
    "#9C27B0",
    "#607D8B",
  ];
  return colors[Math.floor(Math.random() * colors.length)];
};

const saveEvents = () => {
  localStorage.setItem("events", JSON.stringify(events.value));
};

const loadEvents = () => {
  const savedEvents = localStorage.getItem("events");
  if (savedEvents) {
    // 加载时过滤掉已删除的事件
    events.value = JSON.parse(savedEvents).filter(
      (event: Event) => event.status === 1
    );
  }
};

// 辅助函数
const logApiError = (error: any) => {
  console.group("API错误详情");
  console.log("错误对象:", error);
  if (error.response) {
    console.log("状态码:", error.response.status);
    console.log("响应数据:", error.response.data);
    console.log("请求配置:", error.config);
  } else if (error.request) {
    console.log("请求对象:", error.request);
  }
  console.groupEnd();
};

const formatDate = (date: Date) => {
  return date.toLocaleDateString("zh-CN", { month: "short", day: "numeric" });
};

const formatTime = (time: string) => {
  return time.slice(0, 5);
};

// 修改getDayName使其支持1=周一, ..., 7=周日
const getDayName = (dayIndex: number) => {
  const names = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  // dayIndex: 1=周一, ..., 6=周六, 0/7=周日
  if (dayIndex === 0 || dayIndex === 7) return names[0];
  return names[dayIndex];
};

const isSameDay = (date1: Date, date2: Date) => {
  return (
    date1.getFullYear() === date2.getFullYear() &&
    date1.getMonth() === date2.getMonth() &&
    date1.getDate() === date2.getDate()
  );
};

const isCurrentTime = (day: number, time: string) => {
  const now = new Date();
  const today = now.getDay(); // 0=周日, 1=周一, ..., 6=周六
  if (day !== today + 1) return false; // 我们的day是1=周日, 2=周一,...,7=周六

  const [hour, minute] = time.split(":").map(Number);
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();

  return (
    currentHour === hour &&
    currentMinute >= minute &&
    currentMinute < minute + 40
  );
};

// 初始化
onMounted(() => {
  initializeAcademicCalendar();
  loadEvents();
});
</script>

<style scoped>
/* 内容容器 */
.container {
  width: 90%;
  margin: 0 auto;
  padding: 36px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-blue);
  overflow: hidden;
  overflow: visible;
  backdrop-filter: blur(20px);
  border: 1px solid var(--border-light);
}

.timetable-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.timetable-container {
  width: 100%;
}

.timetable-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 24px 0;
  gap: 24px;
  flex-wrap: wrap;
  padding: 20px;
  background: linear-gradient(
    135deg,
    rgba(162, 89, 236, 0.05) 0%,
    rgba(91, 110, 225, 0.05) 100%
  );
  border-radius: var(--radius-lg);
  border: 1px solid var(--border-light);
}

.semester-selector {
  flex: 1;
  min-width: 200px;
}

.semester-selector select {
  width: 100%;
  padding: 12px 16px;
  border-radius: var(--radius-lg);
  border: 2px solid var(--border-light);
  background-color: var(--bg-primary);
  color: var(--primary-blue);
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: var(--shadow-sm);
}

.semester-selector select:focus {
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 3px rgba(91, 110, 225, 0.1);
}

.week-navigation {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  justify-content: center;
}

.nav-btn {
  background: var(--bg-primary);
  border: 2px solid var(--border-light);
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: var(--primary-blue);
  font-weight: 600;
  box-shadow: var(--shadow-sm);
}

.nav-btn:hover {
  background: var(--light-blue);
  border-color: var(--primary-blue);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.week-title {
  font-size: 18px;
  font-weight: 700;
  color: var(--primary-purple);
  min-width: 260px;
  text-align: center;
}

.action-buttons {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.add-btn {
  height: 42px;
  padding: 0 20px;
  border-radius: var(--radius-xl);
  background: var(--bg-primary);
  color: var(--primary-purple);
  border: 2px solid var(--border-light);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: var(--shadow-sm);
}

.add-btn:hover {
  background: var(--light-purple);
  border-color: var(--primary-purple);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.sync-btn {
  height: 42px;
  padding: 0 24px;
  border-radius: var(--radius-xl);
  background: var(--gradient-blue);
  color: #fff;
  border: none;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;
}

.divider {
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, #a9c5f7 0%, #e9ddfe 100%);
  margin: 24px 0;
}

.timetable-header {
  display: flex;
  background: #f5f3fe;
  border-bottom: 1px solid #e9ddfe;
  min-width: fit-content;
}

.time-column {
  width: 80px;
  min-width: 80px;
  padding: 12px;
  text-align: center;
  font-weight: bold;
  color: #5b6ee1;
  position: sticky;
  left: 0;
  background: #f5f3fe;
  z-index: 1;
  box-sizing: border-box;
}

.day-header {
  flex: 1;
  min-width: 120px;
  padding: 8px;
  text-align: center;
  font-weight: bold;
  color: #5b6ee1;
  border-left: 1px solid #e9ddfe;
  line-height: 1.4;
  box-sizing: border-box;
}

.day-header.today {
  background: #e9ddfe;
  color: #a259ec;
}

.timetable-body {
  width: 100%;
  overflow-x: auto;
  background: #fff;
  /*max-height: calc(100vh - 250px);*/
  max-height: none;
  overflow-y: visible;
  -ms-overflow-style: none;
  scrollbar-width: none;
  min-width: fit-content;
}

.timetable-body::-webkit-scrollbar {
  display: none;
}

.timetable-row {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  min-width: fit-content;
  min-height: 100px;
}

.time-slot {
  width: 80px;
  min-width: 80px;
  padding: 8px;
  text-align: center;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  position: sticky;
  left: 0;
  background: white;
  z-index: 1;
  box-sizing: border-box;
}

.day-slot {
  flex: 1;
  min-width: 120px;
  min-height: 80px;
  padding: 4px;
  border-left: 1px solid #f0f0f0;
  position: relative;
  box-sizing: border-box;
}

.day-slot.current-time {
  background: rgba(165, 180, 252, 0.1);
}

.course-item {
  margin: 2px;
  padding: 8px;
  border-radius: 8px;
  color: white;
  font-size: 13px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.schedule-item {
  position: absolute;
  left: 2px;
  right: 2px;
  padding: 4px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  cursor: pointer;
  box-sizing: border-box;
  z-index: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.course-item:hover,
.schedule-item:hover {
  z-index: 2;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}

.course-name,
.schedule-name {
  font-weight: bold;
  margin-bottom: 2px;
}

.course-time,
.schedule-time {
  font-size: 11px;
  opacity: 0.9;
}

.course-location,
.schedule-location {
  font-size: 12px;
  opacity: 0.9;
}

.course-teacher {
  font-size: 11px;
  opacity: 0.9;
  font-style: italic;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  overflow-y: auto;
  padding: 20px 0;
}

.modal-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
  margin: 0 auto;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content h3 {
  margin-top: 0;
  color: #5b6ee1;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.time-group {
  display: flex;
  gap: 16px;
}

.time-group > div {
  flex: 1;
}

.week-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.week-range select {
  flex: 1;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 24px;
}

.delete-btn {
  background: #f44336;
  margin-right: auto;
}

.nav-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f0f0f0;
}

.icon-plus {
  font-size: 14px;
}

@media (max-width: 768px) {
  .flow-container {
    padding: 15px;
    border-radius: 0;
  }

  .timetable-body {
    max-height: calc(100vh - 200px);
  }

  .time-group {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
